import os.path
from time import sleep

import yaml
from selenium import webdriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait

from src.web.wework.main_page import MainPage


class LoginPage:

    def __init__(self, driver=None):
        if driver is None:
            # chrome_options = webdriver.ChromeOptions()
            # chrome_options.binary_location = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
            # chrome_options.add_argument(r'--lang=zh-CN')
            # self.driver = webdriver.Chrome(chrome_options=chrome_options,executable_path=r'C:\APP\driver\chrome\chromedriver.exe')
            self.driver = webdriver.Chrome()
            # self.driver = webdriver.Firefox()
        self.driver.maximize_window()
        self.driver.implicitly_wait(10)
        self.driver.get("https://work.weixin.qq.com/wework_admin/frame")

    def login(self):
        """登录"""
        # 如果存在cookies文件
        if os.path.exists("cookies.yml"):
            with open("cookies.yml", encoding="utf-8") as file:
                cookies = yaml.safe_load(file)
            for cookie in cookies:
                self.driver.add_cookie(cookie)
            self.driver.refresh()
        else:
            # 不存在cookies文件，需要扫码登录
            # WebDriverWait  显示等待来控制 扫码登录操作
            url = self.driver.current_url
            print(url)
            WebDriverWait(self.driver, 60, 1).until(expected_conditions.url_changes(url))
            # sleep(10)
            # 扫码登录成功后，获取cookies的信息
            cookies = self.driver.get_cookies()
            # 将cookies的信息写入文件中
            with open("cookies.yml", "w", encoding="utf-8") as file:
                yaml.safe_dump(cookies, file)

        return MainPage(self.driver)
